import { matchPath } from 'react-router-dom'
import log from './log'

const matchRoute = (store, request, routes = {}) => {
  const url = request.path
  const params = request.query
  const result = {
    entry: null,
    tasks: [],
    matches: [],
  }

  for (const key in routes) {
    const route = routes[key]
    const match = matchPath(url, route)

    if (match && route.title) {
      result.entry = route
    }
    if (match && route.setData) {
      result.tasks.push( store.dispatch(route.setData({ ...match.params, ...params })) )
      result.matches.push( match )
    }
  }

  log.info(`[REQUEST] path: ${url}, route: ${JSON.stringify({
    path: result.entry ? result.entry.path : null,
    state: store.getState(),
    query: params,
    matches: result.matches,
  })}`)

  return result
}

export default matchRoute